package exercise;

import eventservice.Event;
import eventservice.EventChannel;
import eventservice.RemotelyPullable;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import suppliers.SimpleEvent;

class PullConsumer {

	private static EventChannel channel;
	private static String channelName;
	private static RemotelyPullable handle;
	private static boolean subscribed;

	public static void main(String[] args) {
		if (args.length < 2) {
			System.err.println("Usage: PullConsumer host channel_name");
			return;
		}

		String host = args[0];
		channelName = args[1];

		Registry registry = null;
		try {
			registry = LocateRegistry.getRegistry(host);
		} catch (RemoteException e) {
			System.err.println("Cannot locate registry at host '" + host + "': " + e.getMessage());
			return;
		}

		channel = null;
		try {
			channel = (EventChannel) registry.lookup(channelName);
		} catch (Exception e) {
			System.err.println("Cannot lookup channel '" + channelName + "': " + e.getMessage());
			return;
		}

		handle = null;
		try {
			handle = channel.subscribePullConsumer();
			subscribed = true;
		} catch (RemoteException e) {
			System.err.println("Cannot register supplier to channel '" + channelName + "': " + e.getMessage());
			return;
		}

		if (handle == null) {
			System.err.println("Supplier is already registered in '" + channelName + "'.");
			return;
		}

		Scanner scanner = new Scanner(System.in);
		System.out.print("> ");
		while (scanner.hasNextLine()) {
			String line = scanner.nextLine().toLowerCase();
			if (line.contains("pull")) {
				pull();
			} else if (line.contains("quit")) {
				quit();
			} else {
				System.err.println("Unrecognised command: '"+line+"'");
			}
			System.out.print("> ");
		}

		if (subscribed == true) {
			System.err.println("Please use the quit command next time you want to exit! Thank you!");
			quit();
		}

	}

	private static void pull() {
		try {
			System.out.println("Pulling...");
			Event e = handle.pull();
			String m = ((SimpleEvent) e).toString();
			if (m.isEmpty()) {
				System.out.println("Pulled empty event.");
			} else {
				System.out.println("Pulled event: " + m);
			}
		} catch (RemoteException ex) {
			Logger.getLogger(PullConsumer.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	private static void quit() {
		try {
			channel.unsubscribe(handle);
			subscribed = false;
			System.out.println("Good bye!");
			System.exit(0);
		} catch (RemoteException e) {
			System.err.println(
					"Cannot unsubscribe consumer from channel '" + channelName + "': " + e.getMessage());
		}
	}



}

